<template>
  <div class="sc-design">
    <q-form @submit="onSubmit" @reset="onReset" ref="loginForm">
      <q-tabs
        v-model="loginType"
        active-color="primary"
        indicator-color="primary"
        align="left"
        :breakpoint="0"
        narrow-indicator
        class="text-black"
        @click="handleClick"
        :stretch="true"
      >
        <q-tab :name="loginTypes.qrcodeLogin" label="扫码登录" />
        <q-tab :name="loginTypes.usernameLogin" label="账户登录" />
      </q-tabs>
      <div class="q-gutter-y-sm">
        <q-tab-panels v-model="loginType" class="text-center">
          <q-tab-panel :name="loginTypes.qrcodeLogin" class="q-col-gutter-y-sm">
            <q-img :src="loginurl" v-if="islogin == 0"></q-img>
            <div
              icon="success"
              title="扫码成功"
              v-else-if="islogin == 1"
              subTitle="等待手机确认操作"
              class="login_status"
            >
              <p>
                <q-icon
                  name="fa fa-check-circle fa-lg fa-5x"
                  style="color: #67c23a; font-size: 100px"
                />
              </p>
              <p></p>
              <p class="status_text">扫码成功</p>
              <p class="status_text">等待手机确认操作</p>
              <p class="status_reload">
                <btn type="primary" size="medium" @click="resetQrcode"
                  >刷新二维码</btn
                >
              </p>
            </div>
            <div
              icon="warning"
              title="已取消登录"
              v-else-if="islogin == 2"
              subTitle="请刷新二维码重新扫码"
              class="login_status"
            >
              <p>
                <q-icon
                  name="fa fa-exclamation-circle"
                  style="color: #e6a23c; font-size: 100px"
                />
              </p>
              <p></p>
              <p class="status_text">已取消登录</p>
              <p class="status_text">请刷新二维码重新扫码</p>
              <p class="status_reload">
                <btn type="primary" size="medium" @click="resetQrcode"
                  >刷新二维码</btn
                >
              </p>
            </div>
            <p v-if="islogin == 0" style="margin-bottom: 120px">微信扫码登录</p>
            <div class="empower" v-if="formAuth">
              {{ powerInfo.operators }}，您当前还没有权限！向管理员
              <a href="javascript:void(0)" @click="ApplyPower()">申请权限</a>
            </div>
          </q-tab-panel>
          <q-tab-panel
            :name="loginTypes.usernameLogin"
            class="q-col-gutter-y-sm q-top"
          >
            <div class="row">
              <div class="col">
                <q-input
                  rounded
                  outlined
                  clearable
                  clear-icon="cancel"
                  v-model="loginData.gscode"
                  dense
                  debounce="1000"
                  label="分公司"
                  :rules="[(val) => (val && val.length > 0) || '请输入分公司']"
                >
                  <template v-slot:prepend>
                    <img
                      style="margin-left: 17px"
                      src="../../statics/img/business.png"
                      alt=""
                      sizes=""
                      srcset=""
                    />
                    <!-- <q-icon name="business" /> -->
                  </template>
                </q-input>
              </div>
            </div>
            <div class="row">
              <div class="col">
                <q-input
                  rounded
                  outlined
                  clearable
                  clear-icon="cancel"
                  v-model="loginData.username"
                  dense
                  debounce="1000"
                  label="用户名"
                  :rules="[(val) => (val && val.length > 0) || '请输入用户名']"
                >
                  <template v-slot:prepend>
                    <img
                      style="margin-left: 17px"
                      src="../../statics/img/person.png"
                      alt=""
                      sizes=""
                      srcset=""
                    />
                    <!-- <q-icon name="person" /> -->
                  </template>
                </q-input>
              </div>
            </div>
            <div class="row">
              <div class="col">
                <q-input
                  rounded
                  outlined
                  clearable
                  clear-icon="cancel"
                  :type="isPwd ? 'password' : 'text'"
                  v-model="loginData.password"
                  dense
                  debounce="1000"
                  label="密码"
                  :rules="[(val) => (val && val.length > 0) || '请输入密码']"
                >
                  <template v-slot:prepend>
                    <img
                      style="margin-left: 19px"
                      src="../../statics/img/lock.png"
                      alt=""
                      sizes=""
                      srcset=""
                    />
                    <!-- <q-icon name="lock" /> -->
                  </template>
                  <template v-slot:append>
                    <q-icon
                      :name="isPwd ? 'visibility_off' : 'visibility'"
                      class="cursor-pointer"
                      @click="isPwd = !isPwd"
                    />
                  </template>
                </q-input>
              </div>
            </div>
          </q-tab-panel>
        </q-tab-panels>
        <div class="q-mx-md login_vbtn">
          <div class="row" v-show="show">
            <div class="col">
              <q-btn
                dense
                unelevated
                label="登 录"
                size="18px"
                class="full-width no-border-radius login_btn"
                type="submit"
                :loading="loginLoading"
              >
                <template v-slot:loading>
                  <q-spinner-ios class="on-left" />
                  登录...
                </template>
              </q-btn>
            </div>
          </div>
        </div>
      </div>
    </q-form>
  </div>
</template>

<script>
import {
  loginPhone,
  loginUsername,
  loginApi,
  toOauthLogin,
  loginqrcodeApi,
  get_LoginTokenApi,
  softwareloginApi,
  save_power_sqApi
} from '@/api/user'
import commonUtil from '@/utils/commonUtil'
import { removeToken, setLoginData, setToken } from '@/utils/localStorage'

const iconObject = {
  // weixin: {
  //   class: { iconName: 'iconweixin', color: 'text-grey' },
  //   size: '22px'
  // },
  // zhifubao: {
  //   class: {
  //     iconName: 'iconzhifubao',
  //     color: 'text-grey'
  //   },
  //   size: '20px'
  // },
  // taobao: {
  //   class: { iconName: 'icontaobao', color: 'text-grey' },
  //   size: '22px'
  // },
  // weibo: {
  //   class: { iconName: 'iconweibo', color: 'text-grey' },
  //   size: '20px'
  // },
  github: {
    class: { iconName: 'iconhuaban88', color: 'text-grey' },
    size: '23px',
    type: 'link'
  },
  gitee: {
    class: { iconName: 'icongitee', color: 'text-grey' },
    size: '23px',
    type: 'link'
  },
  baidu: {
    class: { iconName: 'iconbaidu', color: 'text-grey' },
    size: '23px',
    type: 'link'
  },
  qq: {
    class: { iconName: 'iconqq', color: 'text-grey' },
    size: '23px',
    type: 'link'
  }
}
const loginTypes = {
  usernameLogin: 'usernameLogin',
  qrcodeLogin: 'qrcodeLogin'
}
export default {
  name: 'Login',
  data() {
    return {
      iconObject,
      iconActive: {
        weibo: 'grey'
      },
      loginTypes,
      loginType: loginTypes.qrcodeLogin,
      loginData: {
        username: '15876515239',
        password: '123456',
        gscode: 'A001',
        phone: null,
        rememberMe: true,
        phonePassword: null
      },
      accept: false,
      isPwd: true,
      loginLoading: false,
      name: null,
      password: null,
      gscode: 'A001',
      account: 'admin',
      islogin: 0,
      loginurl: '',
      show: 1,

      powerInfo: {},
      formAuth: false,
      softwaredata: {}
    }
  },
  created() {
    this.initQrcode()
  },
  mounted() {
    // let url = commonUtil.currentURL()
    // this.softwaredata = commonUtil.getURLParameters(decodeURIComponent(url))
    // if (this.softwaredata != null) {
    //   this.softwarelogin()
    // } else {
      this.get_LoginToken()
    // }
  },
  methods: {
    get_LoginToken() {
      this.formAuth = false
      var gidstr = commonUtil.getUrlParam('gid')
      if (gidstr) {
        get_LoginTokenApi({
          action: 'get_LoginToken',
          gid: gidstr
        }).then((res) => {
          if (res.res_code) {
            var obj = res.res_model
            if (obj.allowlogin) {
              // window.open(decodeURIComponent(obj.url), '_self')
              setToken(obj.data.user.token)
              setLoginData(obj.data.user)

              commonUtil.notifySuccess('正在登录，请稍等......')
              setTimeout(() => {
                this.$router.push({path: '/'});
              }, 2000);

            } else {
              //显示申请授权
              this.powerInfo = obj
              this.formAuth = true
            }
          } else {
            commonUtil.notifyError(res.res_msg ? res.res_msg : '数据异常！')
          }
        })
      }
    },
    softwarelogin() {
      commonUtil.showLoading('正在登录，请稍候')
      softwareloginApi({
        gscode: this.softwaredata.gscode,
        guestcode: this.softwaredata.reguserno,
        operators: this.softwaredata.Operators
      }).then((res) => {
        if (res.code == '0') {
          setToken(res.data.user.token)
          setLoginData(res.data.user)
          setTimeout(() => {
            commonUtil.hideLoading()
            commonUtil.notifySuccess('登录成功')
          }, 1000)
          this.$router.push({
            path: '/'
          })
        } else {
          commonUtil.notifyError('登录失败，请核对账号密码')
        }
      })
    },
    ApplyPower() {
      this.save_power_sq()
    },
    save_power_sq() {
      save_power_sqApi({
        action: 'save_power_sq',
        powers: JSON.stringify({
          softtype: 'SQ',
          Ywtype: '申请',
          Gscode: this.powerInfo.gscode,
          Applyuser: this.powerInfo.operators,
          Opername: this.powerInfo.operators,
          sqopenid: this.powerInfo.openid,
          Status: false,
          Sqstatus: '待授权',
          Remarks: '申请登录权限',
          Writeuser: this.powerInfo.operators,
          Srctype: 'SQ'
        }),
        menunames: JSON.stringify([
          {
            ptype: 'allowlogin',
            menuid: 'SQ',
            ismobile: false,
          }
        ]),
        guestcode: this.powerInfo.guestcode,
        guestname: this.powerInfo.guestname,
        gscode: this.powerInfo.gscode,
        codetoken: localStorage.rqrcodekey
      }).then((res) => {
        if (res.res_code) {
          commonUtil.notifySuccess(
            res.res_msg ? res.res_msg : '登录申请已经【微信发送】给系统管理员！'
          )
        } else {
          commonUtil.notifyError(res.res_msg ? res.res_msg : '数据异常！')
        }
      })
    },

    onSubmit() {
      this.login()
    },
    handleClick() {
      if (this.loginType === this.loginTypes.usernameLogin) {
        this.qrcodestop()
        this.show = 1
      } else {
        this.initQrcode()
        this.show = 0
      }
    },
    login() {
      this.loginLoading = true
      setTimeout(() => {
        if (this.loginType === this.loginTypes.usernameLogin) {
          this.loginUsername()
        } else {
          this.initQrcode()
        }
      }, 1000)
    },
    qrcodestop() {
      clearInterval(window.invl)
      this.clear_data()
      this.islogin = 0
    },
    clear_data() {
      window.localStorage.removeItem('rqrcodekey')
    },
    initQrcode() {
      this.isreset = false
      this.clear_data()
      this.getQRcodeStauts()
      window.invl = setInterval(this.getQRcodeStauts, 3000)
    },
    resetQrcode() {
      this.qrcodestop()
      this.initQrcode()
    },
    getQRcodeStauts() {
      let qrcodekey = localStorage.rqrcodekey
      loginqrcodeApi({
        qrcodeKey: qrcodekey
      }).then((res) => {
        localStorage.setItem('rqrcodekey', res.qrcodekey)
        let url = window.location.href
        let posturl = 'http://wxapp.inheart.cn'
        if (url.indexOf('192.168') > 0 || url.indexOf('localhost') > 0) {
          posturl = 'http://192.168.0.88:188'
        }
        let qrdata = encodeURIComponent(
          posturl + '/login/AdminLogin.aspx?qrcode_key=' + res.qrcodekey
        )
        this.loginurl = 'http://wx.inheartsoft.com/2DCode.ashx?data=' + qrdata
        switch (res.status) {
          case 'QRCODE_SCAN_NEVER':
            break
          case 'QRCODE_SCAN_ING':
            this.islogin = 1
            break
          case 'QRCODE_SCAN_SUCC':
            if (res.code === 0) {
              setToken(res.data.user.token)
              setLoginData(res.data.user)
              clearInterval(window.invl)
              this.qrcodestop()
              commonUtil.notifySuccess('登录成功')
              this.$router.push({
                path: '/'
              })
            }
            break
          case 'QRCODE_SCAN_FAIL':
            clearInterval(window.invl)
            this.qrcodestop()
            this.islogin = 2
            break
        }
      })
    },

    loginPhone() {
      loginPhone(this.loginData)
        .then((response) => {
          this.success()
        })
        .catch((err) => {
          this.loginLoading = false
        })
    },
    loginUsername() {
      loginUsername({
        gscode: this.gscode,
        username: this.loginData.username,
        password: this.loginData.password
      })
        .then((response) => {
          if (response.code == '0') {
            setToken(response.data.token)
            setLoginData(response.data.user)
            this.success()
          } else {
            commonUtil.notifyError('登录失败，请核对账号密码')
            this.loginLoading = false
          }
        })
        .catch((err) => {
          this.loginLoading = false
        })
    },
    success() {
      commonUtil.notifySuccess('登录成功')
      this.loginLoading = false
      this.$router.push({
        path: '/'
      })
    },
    onReset() {
      this.loginData = commonUtil.resetObj(this.loginData)
    },
    mouseOver(iconKey, event) {
      this.activeForLoginType(iconKey, 'text-primary')
    },
    mouseLeave(iconKey, event) {
      this.activeForLoginType(iconKey, 'text-grey')
    },
    activeForLoginType(iconKey, targetColor) {
      this.iconObject[iconKey].class.color = targetColor
    },
    thirdLogin(iconKey, event) {
      window.open(toOauthLogin(iconKey, '/'), '_self')
    }
  },
  computed: {
    loginIcon: function () {
      return this.iconObject
    }
  }
}
</script>

<style scoped>
.sc-design,
.q-form {
  width: 100%;
  height: 100%;
}
.q-form > .q-gutter-y-sm,
.text-black .q-tab,
.q-gutter-y-sm,
.text-center,
.login .q-top {
  margin: 0;
}

.sc-design
  >>> .q-tabs--not-scrollable
  .q-tabs__content
  > .q-tab:last-child
  .non-selectable
  .q-tab__label {
  margin-left: 9px;
}

.empower {
  font-size: 16px;
  color: #f00;
  text-align: center;
  overflow: hidden;
  margin-top: 15px;
  position: absolute;
  bottom: -36px;
  left: 50px;
}
.empower > a {
  color: #00f !important;
  font-weight: bold;
  text-decoration: underline !important;
  letter-spacing: 0.5px;
  padding-left: 2px;
  font-size: 16px !important;
}

.q-layout {
  background: url(https://wxapp.inheart.cn/img/bg.png) no-repeat;
  background-size: cover;
  position: relative;
}
.flip-list-move {
  transition: transform 1s;
}
.q-tab {
  background: #ebf4fd;
  width: 50%;
}

.q-tab-panels,
.login .q-gutter-y-sm {
  background: #ebf4fd;
}

.self-stretch {
  width: 100%;
  text-align: center;
  font-size: 20px;
  color: #333;
  white-space: nowrap;
  cursor: pointer;
}

.text-black {
  color: #d0d0d0 !important;
  margin: 0 0 49px;
}
.sc-design >>> .q-tabs--not-scrollable .q-tabs__content {
  margin-top: 19px;
}

.sc-design >>> .q-tab__content {
  padding: 0;
}
.sc-design >>> .q-tab__label {
  line-height: normal;
}
.sc-design >>> .text-primary {
  color: #a83f3f !important;
}
.sc-design >>> .text-primary .q-tab__label {
  font-weight: bold;
}

.login .q-img {
  padding: 0;
  margin: 0;
  margin: 8px auto 19px;
  position: relative;
}

.login p {
  font-size: 16px;
  color: #333;
  text-align: center;
  letter-spacing: 1px;
  overflow: hidden;
  font-weight: 100;
}

.sc-design >>> .q-hoverable:hover > .q-focus-helper {
  background: transparent;
}

.sc-design >>> .q-gutter-y-sm .q-tab-panels .q-top > div {
  padding: 0;
  padding-bottom: 10px;
}
.sc-design >>> .row .items-start {
  width: 316px;
}
.sc-design >>> .q-field__inner {
  height: 42px;
}
.sc-design >>> .q-field--dense .q-field__control {
  height: 42px;
  border-radius: 5px;
  padding: 0;
  border: 0;
  outline: 0;
  color: transparent;
}
.sc-design >>> .q-field--outlined .q-field__control:hover:before {
  border-color: #bfbfbf;
}

.sc-design >>> .q-field__control-container {
  background: #fff;
  width: 262px;
  max-width: 261px;
  height: 40px;
  margin-top: 1px;
  padding: 0 10px;
  border-radius: 5px;
}
.sc-design >>> .q-field--dense .q-field__append {
  height: 42px;
  background: #fff;
  padding-right: 6px;
}
.sc-design >>> .q-field--dense.q-field--float .q-field__label {
  padding-left: 15px;
  color: #333;
}
.sc-design >>> .q-field--dense .q-field__prepend {
  width: 54px;
  height: 42px !important;
  padding: 0;
  border-right: 1px solid #bfbfbf;
}
.sc-design >>> .q-field--outlined .q-field__control:before {
  border: 1px solid #bfbfbf;
}

.sc-design >>> .q-field--error .q-field__label,
.sc-design >>> .q-field--dense .q-field__label {
  padding: 0 10px;
}

.sc-design >>> .login_vbtn {
  width: 368px;
  margin: auto;
}
.sc-design >>> .login_vbtn .blick {
  letter-spacing: 22px;
  text-indent: 12px;
}

.sc-design >>> .login_status {
  margin: 0 auto 130px;
}
.sc-design >>> .status_reload btn {
  display: inline-block;
  width: 100px;
  height: 36px;
  line-height: 36px;
  padding: 0;
}
</style>
